package com.situ.mall.controller.front;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.situ.mall.pojo.entity.Order;
import com.situ.mall.pojo.entity.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.mall.pojo.entity.User;
import com.situ.mall.service.IUserService;
import com.situ.mall.util.JSONResult;

import java.util.List;

@Controller
@RequestMapping("/user")
public class FrontUserController {
	@Autowired
	private IUserService userService;

	// 检测session中用户是否登录
	@ResponseBody
	@RequestMapping("/checkUserLogin.shtml")
	public JSONResult checkUserLogin(HttpSession session) {
		User user = (User) session.getAttribute("user");
		return user != null ? JSONResult.success("已经登录") : JSONResult.error("没有登录");
	}

	// 转到弹出登录框
	@RequestMapping("/getLogin.shtml")
	public String getLogin() {
		return "front/login-min";
	}

	// 转到大登录页面
	@RequestMapping("/bigLogin.shtml")
	public String bigLogin() {
		return "front/login";
	}

	// 注销登录并回到商城主页
	@RequestMapping("/logout.shtml")
	public String logout(HttpSession session) {
		session.invalidate();
		return "forward:/index.shtml";
	}

	// 登录判断，若正确建立session会话
	@ResponseBody
	@RequestMapping("/login.shtml")
	public JSONResult login(String username, String password, HttpSession session, HttpServletRequest req) {
		User user = userService.selectUserLogin(username, password);
		if (user != null) {
			session.setAttribute("user", user);
			return JSONResult.success("登陆成功");
		}
		return JSONResult.error("登录失败");
	}

	// 跳转到用户全部订单页面
	@RequestMapping("/ucOrder.shmtl")
	public String getUCOrder(HttpSession session, Model model) {
		User user = (User) session.getAttribute("user");
		List<Order> orderListVO = userService.selectUserOrder(user.getId());
		List<OrderItem> orderItemList = userService.selectUserOrderItem(user.getId());
		model.addAttribute("orderListVO", orderListVO);
		model.addAttribute("orderItemList", orderItemList);
		return "/front/uc-order";
	}

}
